package com.health.auth.service;

import com.alibaba.fastjson.JSONObject;
import com.health.common.core.constant.CacheConstants;
import com.health.common.core.constant.Constants;
import com.health.common.core.domain.R;
import com.health.common.core.exception.CaptchaException;
import com.health.common.core.exception.ServiceException;
import com.health.common.core.utils.JwtUtils;
import com.health.common.core.utils.StringUtils;
import com.health.common.redis.service.RedisService;
import com.health.common.security.utils.SecurityUtils;
import com.health.personal.api.RemotePersonalService;
import com.health.personal.api.domain.dto.TDoctorDto;
import com.health.personal.api.model.JwtConstants;
import com.health.personal.api.model.JwtResponse;
import com.health.personal.api.model.LoginDoctor;
import com.health.personal.api.model.TokenConstants;
import com.health.personal.api.model.po.TDoctorPo;
import com.health.system.api.model.LoginUser;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author : Zzs
 * @description :
 * @createDate : 2024/12/12 下午10:36
 */
@Slf4j
@Component
public class DoctorService {

    @Autowired
    private RemotePersonalService remotePersonalService;
    @Autowired
    private SysRecordLogService recordLogService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = CacheConstants.EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    /**
     * 登录
     * @param email
     * @param pwd
     * @return
     */
    public LoginDoctor login(String email, String pwd) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(email, pwd))
        {
            recordLogService.recordLogininfor(email, Constants.LOGIN_FAIL, "邮箱/密码必须填写");
            throw new ServiceException("邮箱/密码必须填写");
        }
        R<TDoctorPo> login = remotePersonalService.login(email);
        TDoctorPo data = login.getData();
        if (data==null){
            throw new ServiceException("邮箱不存在！");
        }
        String password = data.getPassword();
        if (!password.equals(pwd)){
            throw new ServiceException("密码错误!！");
        }
        LoginDoctor loginDoctor = new LoginDoctor();

        loginDoctor.settDoctorPo(data);

        return loginDoctor;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginDoctor getLoginDoctor(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        LoginDoctor loginDockor = getLoginDockor(token);
        return loginDockor;
    }
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginDoctor getLoginDockor(String token)
    {
        LoginDoctor user = null;
        try
        {
            if (StringUtils.isNotEmpty(token))
            {
                String userkey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                return user;
            }
        }
        catch (Exception e)
        {
            log.error("获取用户信息异常'{}'", e.getMessage());
        }
        return user;
    }
    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void DockerToken(LoginDoctor loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    private String getTokenKey(String token)
    {
        return ACCESS_TOKEN + token;
    }


    /**
     * 退出登录
     */
    public void logout(HttpServletRequest request) {
        // 从请求头 获取token
        String token = request.getHeader(TokenConstants.TOKEN);
        // 反向解析出userKey
        String userKey = JwtUtils.getUserKey(token);
        // 获取用户信息
        redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}

